import { makeAutoObservable } from 'mobx'
import { AddProposal, DeleteProposal, GetProposalById, GetProposals, RewriteProposal, SendProposal } from '../requests'
import auth from './auth'
import { ProposalDto } from '../dtos'
import auto from './auto'

export default new (class Proposals {
    list: string[][] = []
    proposal: ProposalDto | undefined
    constructor() {
        makeAutoObservable(this)
    }
    SetProposals() {
        GetProposals().then((data) => {
            this.list = []
            if (data.statusCode == '401') {
                auth.LogOut()
            } else {
                for (const i in data)
                    this.list.push([
                        data[i].status.code,
                        data[i].id,
                        data[i].city.code,
                        data[i].auto.autoCategory.code + ' ' + data[i].auto.model.code,
                    ])
            }
        })
    }
    SetProposalData(id: string) {
        GetProposalById(id).then((data) => {
            if (data.statusCode == '401') {
                auth.LogOut()
            } else if (data.statusCode == '404') {
                this.list = []
            } else {
                this.proposal = data
                auto.category = ['', data.auto.autoCategory.code]
                auto.model = ['', data.auto.model.code]
                auto.city = ['', data.city.code]
            }
        })
    }
    SortBy(k: number) {
        this.list.sort((a, b) => a[k].toString().localeCompare(b[k].toString()))
    }
    Add(requestBody: ProposalDto) {
        if (requestBody)
            AddProposal(requestBody).then((data) => {
                if (data.statusCode == '401') {
                    auth.LogOut()
                } else {
                    this.SetProposals()
                }
            })
    }
    Delete(id: string) {
        if (confirm('Точно удалить?'))
            DeleteProposal(id).then((data) => {
                if (data.statusCode == '401') {
                    auth.LogOut()
                } else {
                    this.SetProposalData(id)
                }
            })
    }
    Rewrite(requestBody: ProposalDto) {
        if (requestBody)
            RewriteProposal(requestBody).then((data) => {
                if (data.statusCode == '401') {
                    auth.LogOut()
                } else {
                    this.SetProposalData(requestBody.id)
                }
            })
    }
    Send(id: string) {
        this.proposal = undefined
        SendProposal(id).then((data) => {
            if (data.statusCode == '401') {
                auth.LogOut()
            } else {
                this.SetProposalData(id)
            }
        })
    }
})()
